﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Graphic))]
    [DisallowMultipleComponent]
    public class UIMaterialEffect : MonoBehaviour,IMaterialModifier {

        private Graphic m_graphic;
        private Material m_srcMat;
        private MaterialsEffect m_effMat;

        public MaterialsEffect MaterialsEffect
        {
            get { return m_effMat; }
            set
            {
                if (!m_effMat.Equals(value))
                {
                    m_effMat = value;
                    if (m_srcMat != null)
                    {
                        MaterialsTool.Release(m_srcMat);
                        m_srcMat = null;
                    }
                }
            }
        }

        // Use this for initialization
        void Awake () {
            m_graphic = GetComponent<Graphic>();

	    }

        void OnEnable()
        {
          if(m_graphic != null)  m_graphic.SetMaterialDirty();
        }
        void OnDisable()
        {
            if (m_graphic != null) m_graphic.SetMaterialDirty();
        }
        /// <summary>
        /// 更新canvasRenderer的材质和纹理。在给canvasRenderer设置材质时，会遍历所有IMaterialModifier类型的组件，
        /// 调用IMaterialModifier.GetModifiedMaterial方法，用于重建图像时，获取修改后的Material，来实现遮罩效果。
        /// </summary>
        /// <param name="baseMaterial"></param>
        /// <returns></returns>
        public Material GetModifiedMaterial(Material baseMaterial)
        {
            Material material = baseMaterial;
            if (enabled)
            {
                if(m_srcMat == null)
                {
                    m_srcMat = MaterialsTool.Get(m_effMat);
                }

                if (m_srcMat) material = m_srcMat;
            }
            MaskableGraphic maskableGraphic = this.m_graphic as MaskableGraphic;
            if (maskableGraphic != null)
            {
                return maskableGraphic.GetModifiedMaterial(material);
            }
            return material;
        }

        internal void Save()
        {
            if (m_graphic != null) m_graphic.SetMaterialDirty();
        }


    }
}
